package cn.edu.cqytxy.dao;

import cn.edu.cqytxy.entity.Admin;
import cn.edu.cqytxy.util.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author yinjw
 */
public class AdminDao {


    public Admin selectAdminByUsername(String username)  {

        // 获取数据库连接
        Connection connection = JdbcUtils.getConnection();

        // 组装执行的sql
        String sql = "select * from admin where username = ?";
        System.out.println("sql : " + sql);
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Admin admin = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, username);
            // 获取查询结果并遍历赋值
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                admin = new Admin();
                admin.setId(resultSet.getInt("id"));
                admin.setUsername(resultSet.getString("username"));
                admin.setPassword(resultSet.getString("password"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return admin;
        } finally {
            try {
                if (preparedStatement != null && !preparedStatement.isClosed()) {
                    preparedStatement.close();
                }
                if (resultSet != null && !resultSet.isClosed()) {
                    resultSet.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return admin;
    }

    public boolean updateAdmin(Admin admin) throws SQLException {

        Connection connection = JdbcUtils.getConnection();

        // 关闭自动提交，没有commit时，数据库的查询结果为没变更
        connection.setAutoCommit(false);

        try {
            // TODO 以下为修改admin的代码

            // 提交事务，把全部的变更生效
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();

            // 事务回滚，报错前对数据库变更还原
            connection.rollback();
            return false;
        }


        return false;
    }
}
